/*
 * Copyright 2008 The Microlog project @sourceforge.net
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.sf.microlog.midp.example;

import java.io.IOException;

import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.Item;
import javax.microedition.lcdui.StringItem;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;

import net.sf.microlog.common.format.PatternFormatter;
import net.sf.microlog.core.Level;
import net.sf.microlog.core.Logger;
import net.sf.microlog.core.LoggerFactory;
import net.sf.microlog.midp.appender.RecordStoreAppender;
import net.sf.microlog.midp.rms.RecordStoreLogLoader;

/**
 * An example midlet that shows how to use the <code>RecordStoreAppender</code>
 * This requires MIDP 1.0 or greater.
 * 
 * @author Johan Karlsson
 * @since 1.1
 */
public class RecordStoreLogMidlet extends MIDlet implements CommandListener {

	private final static Logger log = LoggerFactory.getLogger();

	private Display display;
	private Form form;
	private Command logCommand;
	private Command loadLogCommand;
	private Command clearLogCommand;
	private Command switchSortOrderCommand;
	private Command exitCommand;
	private int nofLoggedMessages;

	private RecordStoreLogLoader loader;

	public RecordStoreLogMidlet() {
		super();
		RecordStoreAppender appender = new RecordStoreAppender();
		PatternFormatter formatter = new PatternFormatter();
		formatter.setPattern("%r %m %T");
		appender.setFormatter(formatter);
		log.addAppender(appender);
		log.setLogLevel(Level.DEBUG);
		log.info("Setup of log finished");
		log.debug("Message 1");
		log.debug("Message 2");
		log.debug("Message 3");
		log.debug("Message 4");
		log.error("Sending an error message.");

		loader = new RecordStoreLogLoader();
	}

	protected void startApp() throws MIDletStateChangeException {
		log.info("Starting app");

		if (display == null) {
			display = Display.getDisplay(this);
			form = new Form("RecordStoreLogMidlet");
			logCommand = new Command("DoLog", Command.SCREEN, 1);
			form.addCommand(logCommand);
			loadLogCommand = new Command("Load", "Load Log", Command.SCREEN, 2);
			form.addCommand(loadLogCommand);
			clearLogCommand = new Command("Clear", "Clear Log", Command.SCREEN,
					3);
			form.addCommand(clearLogCommand);
			switchSortOrderCommand = new Command("Switch", "Switch Sort Order",
					Command.SCREEN, 4);
			exitCommand = new Command("Exit", Command.EXIT, 1);
			form.addCommand(exitCommand);
			form.setCommandListener(this);
		}

		display.setCurrent(form);
	}

	protected void pauseApp() {
		log.info("Pausing app");

	}

	protected void destroyApp(boolean conditional)
			throws MIDletStateChangeException {
		log.info("Destroying app");
		try {
			log.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		notifyDestroyed();
	}

	public void commandAction(Command command, Displayable displayable) {
		if (command == logCommand) {
			logMessage();
		} else if (command == loadLogCommand) {
			loadLog();
		} else if (command == clearLogCommand) {
			clearLog();
		} else if (command == switchSortOrderCommand) {
			switchSortOrder();
		} else if (command == exitCommand) {
			notifyDestroyed();
		}

	}

	/**
	 * Load the log.
	 */
	private void loadLog() {
		
		int nofLogItems = loader.getNumLogItems();

		StringItem header = new StringItem("#Log records", String
				.valueOf(nofLogItems)
				+ "\r\n");
		header.setLayout(Item.LAYOUT_NEWLINE_AFTER);
		form.append(header);
		
		String logContent = loader.getLogContent();
		
		if (logContent != null) {
			form.deleteAll();
			form.append(logContent);
		}
	}

	/**
	 * Clear the log.
	 */
	private void clearLog() {
		loader.clearLog();
		form.deleteAll();
	}

	/**
	 * Switch the sort order.
	 */
	private void switchSortOrder() {
		loader.switchSortOrder();
	}

	/**
	 * Log a message.
	 */
	private void logMessage() {
		log.debug("User pressed the log button. " + nofLoggedMessages++);
		System.out.println("User pressed the log button. ");
	}

}
